<template>
  <view class="dropdown-menu">
    <view class="dropdown-menu__bar" ref="bar">
      <slot></slot>
    </view>

    <view
        v-if="activeIndex !== null"
        class="dropdown-menu__overlay"
        :style="{ top: overlayTop + 'px', zIndex: overlayZ }"
        @click="close"
    ></view>
  </view>
</template>

<script>
export default {
  name: "DropdownMenu",
  data() {
    return {
      activeIndex: null,
      overlayTop: 0,
      overlayZ: 998
    };
  },
  provide() {
    return {
      dropdownMenu: this
    };
  },
  mounted() {
    // 初始测量
    this.updateOverlayTop();

    // 在窗口大小变化时重新测量（H5）
    if (typeof window !== "undefined" && window.addEventListener) {
      window.addEventListener("resize", this.updateOverlayTop);
    }
  },
  beforeDestroy() {
    if (typeof window !== "undefined" && window.removeEventListener) {
      window.removeEventListener("resize", this.updateOverlayTop);
    }
  },
  methods: {
    updateOverlayTop() {
      return new Promise(resolve => {
        this.$nextTick(() => {
          const query = uni.createSelectorQuery().in(this);
          query.select(".dropdown-menu__bar").boundingClientRect(rect => {
            if (rect) {
              this.overlayTop = rect.bottom;
            }
            resolve();
          }).exec();
        });
      });
    },

    async toggleItem(index) {
      if (this.activeIndex === index) {
        this.close();
        return;
      }
      this.activeIndex = index;
      // 先更新 overlayTop（防止界面高度变化），再打开
      await this.updateOverlayTop();
    },

    close() {
      this.activeIndex = null;
    }
  }
};
</script>

<style scoped>
.dropdown-menu {
  position: relative;
  background-color: #fff;
}

.dropdown-menu__bar {
  display: flex;
  border-bottom: 1px solid #ebedf0;
  background-color: #fff;
  z-index: 10;
}

.dropdown-menu__overlay {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
}
</style>
